package com.itheima.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Result;
import com.itheima.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    //在目标方法执行之前会执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle......");

        String token = request.getHeader("token");
        if (token == null){
            log.warn("令牌不存在！！！");
            Result not_login = Result.error("NOT_LOGIN");
            response.getWriter().write(JSON.toJSONString(not_login));  //序列化：将对象转json格式字符串
            return false;
        }

        //解析token，如果解析失败，返回错误结果（未登录）。
        try {
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            log.info("claims={}", claims);
        } catch (Exception e) {
            log.info("令牌解析失败！！", e.getMessage());
            Result not_login = Result.error("NOT_LOGIN");
            response.getWriter().write(JSON.toJSONString(not_login));  //序列化：将对象转json格式字符串
            return false;

        }
        return true;   //false代表不放行
    }

    //在目标方法执行之后会执行
    /*@Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle......");
    }

    //在目标方法执行之后会执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterHandle......");
    }*/
}
